package com.innovation.chengzhangriji.service;

import android.app.Service;
import android.content.Intent;
import android.text.TextUtils;

import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.preferences.LoginInfo;

public abstract class BaseTimelineService extends Service {

    private ImplNetworkUnavailableListener listener;

    private boolean isRun;

    private String mUserID;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 判断是否有用户登录信息
        LoginInfo login = Config.getLoginInfo(this);
        if (login == null) {
            return super.onStartCommand(intent, flags, startId);
        }
        String userID = login.getUserID();
        // 判断是否正在运行,且用户标识不为空.
        if (isRun && !TextUtils.isEmpty(mUserID)) {
            // 判断未切换用户
            if (mUserID.equals(userID)) {
                return super.onStartCommand(intent, flags, startId);
            }
        }
        // 运行到这里说明第一次运行该服务,或者重新启动了服务.
        isRun = true;
        mUserID = userID;
        listener = new ImplNetworkUnavailableListener();
        onTimelineStartCommand();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isRun = false;
        // DatabaseManager.getInstance(this).closeDbConnections();
    }

    protected abstract void onTimelineStartCommand();

    protected final ImplNetworkUnavailableListener networkUnavailableSampleImpl() {
        return listener;
    }

    protected void networkUnavailable() {
        Intent intent = new Intent();
        intent.setAction(Config.ACTION_NETWORK_UNAVAILABLE);
        sendBroadcast(intent);
    }

    private class ImplNetworkUnavailableListener implements Client.NetworkUnavailableListener {
        @Override
        public void networkUnavailable() {
            BaseTimelineService.this.networkUnavailable();
            stopSelf();
        }
    }
}
